import Shop from '../model/shop'
import { refresh } from '../api/token'
// import { getShopIdData } from '../api/webPageAip/product'
import { getshopid, getjwtdata } from '../utils/getWebAjax'
import { developmentkey } from '../config'
import moment from 'moment'
import redis from '../dbHelper/redis'

const refreshTokenExpiresIn = 14 * 24 * 60 * 60 // 14天 秒
const accessTokenExpiresIn = 60 * 58 // 1小时 秒
const cheackShop = (nourl = []) => {
	if (Array.isArray(nourl) === false) throw new Error('nourl参数必须为数组')
	return async (ctx, next) => {
		// 跳过admin检查shopid
		if (/\/dlyadminapi\/*/.test(ctx.url)) return await next()
		if (nourl.filter((item) => item.test(ctx.url)).length) {
			// 存在jwt的情况下使用jwt中的shopid 跳过请求抖店后台接口逻辑
			const jwtdata = await getjwtdata(ctx)
			if (jwtdata.jwtdata && jwtdata.jwtdata.shop_id) {
				ctx.query.shop_id = jwtdata.jwtdata.shop_id

				await getShopMenbers()
				return
			}

			// 正常刷新也没进入会自动携带相关信息， 防止跨流程调用
			const shopId = await getshopid(ctx)
			if (!shopId.code) {
				const shopIdAsyc = shopId.data.shop_id
				if (shopIdAsyc) {
					ctx.query.shop_id = shopIdAsyc
					// 查询数据库
					await getShopMenbers()
					return
					// return await next()
				} else {
					ctx.body = {
						msg: '获取shopid失败',
						smsg: shopId.msg || '',
					}
					return
					// return await next()
				}
			} else {
				ctx.body = {
					msg: '获取shopid失败',
					smsg: shopId.msg || '',
				}
				return
			}

			// return await next()
		}
		// if(nourl.includes(ctx.url.split('?')[0])) {
		//     return await next()
		// }
		const jumpcheckLogin = [
			/\/api\/user\/checkBuy/,
			/\/jinritemai\/authorize/,
			/\/jinritemai\/callback\/shopbuy/,
			/\/api\/tools\/*/,
			/\/api\/zhangfuai\/*/,
			/\/api\/alipay\/pay/,
			/\/api\/alipay\/cb/,
			/\/api\/aiuser\/*/,
			/\/api\/dlyuser\/*/,
			/\/api\/alipay\/*/,
			/\/api\/test\/*/,
		]
		// 跳过检查进入
		const getchterlist = jumpcheckLogin.filter((item) => item.test(ctx.url))
		// 检查shop_id 必填项
		if (!getchterlist || !getchterlist.length) {
			const outPost = [
				/\/api\/product\/*/,
				/\/api\/shop\/*/,
				/\/api\/material\/*/,
				/\/api\/jiance\/*/,
				/\/api\/editProductLog\/*/,
				/\/api\/qianchuan\/*/,
				/\/api\/hotTitle\/*/
			]
			const outPostList = outPost.filter((item) => item.test(ctx.url))
			if (!outPostList || !outPostList.length) {
				console.log('verifyParams0000', outPostList)
				ctx.verifyParams({
					shop_id: { type: 'string', required: true },
				})
			}
			await getShopMenbers()
			return
		}
		// 排除检查登录接口
		// if(!checkLogin.test(ctx.url)) {

		// }
		await next()
		async function getShopMenbers() {
			// 检查购买情况
			// 跳过登录接口
			const loginurl = /\/api\/user\/shopLogin/
			// const checkLogin = /\/api\/user\/checkBuy/

			if (loginurl.test(ctx.url)) return await next()
			// 跳过白名单
			if (
				global.WhiteList.includes(ctx.query.shop_id + '') ||
				process.env.AOT_ALL_SHOP === 'Y'
			) {
				return await next()
			}
			// shopData = await Shop.findOne({ shop_id: ctx.query.shop_id })
			let shopData = await redis.get(`shopid_${ctx.query.shop_id}`)

			if (!shopData) {
				shopData = await Shop.findOne({ shop_id: ctx.query.shop_id })
				if (shopData) {

					await redis.set(`shopid_${ctx.query.shop_id}`, JSON.stringify(shopData))
					await redis.expire(`shopid_${ctx.query.shop_id}`, 60 * 2)
				}
			} else {
				shopData = JSON.parse(shopData)
			}

			if (!shopData) {
				//
				ctx.body = {
					code: 4388,
					msg: '店铺不存在,请前往购买授权',
					url: process.env.BUY_URL,
				}
				return
			}
			// 调试开发阶段使用
			if (developmentkey) return await next()

			// 检测购买请求
			if (shopData.isBuy === 0) {
				ctx.body = {
					code: 4390,
					msg: '店铺还未订购插件服务，请前往订购',
					url: process.env.BUY_URL,
					title: '未订购',
					button: '前往订购',
				}
				return
			}
			if (shopData.isBuy === 3) {
				ctx.body = {
					code: 4390,
					msg: '店铺订购插件已过期，请前往订购',
					url: process.env.BUY_URL,
					title: '订购已过期',
					button: '前往订购',
				}
				return
			}
			// 检测订购是否过期
			if (moment(shopData.service_end_time * 1000).isBefore(moment())) {
				console.log('订购过期', shopData)
				await Shop.updateOne(
					{
						shop_id: ctx.query.shop_id,
					},
					{
						isBuy: 3,
					}
				)
				ctx.body = {
					code: 4390,
					msg: '店铺订购插件已过期，请前往订购',
					url: process.env.BUY_URL,
					title: '订购已过期',
					button: '前往订购',
				}
				return
			}

			// 检测服务市场授权情况
			if (!shopData.action_type) {
				ctx.body = {
					code: 4390,
					msg: '请前往授权后使用',
					url: process.env.AUTHORIZATION_URL,
					title: '未授权使用',
					button: '前往授权',
				}
				return
			}
			if (shopData.action_type == 1) {
				ctx.body = {
					code: 4390,
					msg: '请打开授权后使用',
					url: process.env.AUTHORIZATION_URL,
					title: '未授权使用',
					button: '前往授权',
				}
				return
			}
			if (shopData.action_type == 3) {
				ctx.body = {
					code: 4390,
					msg: '授权过期请重新授权',
					url: process.env.AUTHORIZATION_URL,
					title: '未授权使用',
					button: '前往授权',
				}
				return
			}

			// 检查 access_token 是否过期  过期|即将过期先去刷新
			// 检查 refresh_token 上次更新是否大于14天
			const {
				access_token,
				refresh_token,
				expires_in,
				updateTime,
				shop_name,
				shop_id,
				service_end_time,
				access_token_update_time = moment().subtract(7, 'days'), // 减去7天
			} = shopData
			// console.log('shopData', shopData)
			const now = Math.floor(new Date().getTime() / 1000)
			const updatetime = Math.floor(
				new Date(access_token_update_time).getTime() / 1000
			)
			const tokenUsed = now - updatetime
			// console.log('expires_in', expires_in, accessTokenExpiresIn, tokenUsed, updatetime, now, access_token_update_time, refreshTokenExpiresIn)
			if (expires_in - accessTokenExpiresIn <= tokenUsed) {
				console.log('access_token 过期')
				// 检查需要调用更新 还是重新授权
				if (tokenUsed >= refreshTokenExpiresIn) {
					// return await next()
					ctx.body = {
						code: 4390,
						msg: '超过14天未使用, 需要重新授权',
						url: process.env.AUTHORIZATION_URL,
						title: '未授权使用',
						button: '前往授权',
					}
					// 重新授权
					// 调用 微信授权接口
					// 更新数据库
					// 返回 4388 错误码
					// 返回 店铺不存在,请前往购买授权
					return
				}
				console.log('access_token', access_token)
				// 调用刷新token接口
				const getShopNewToken = await refresh({
					refresh_token,
					grant_type: 'refresh_token',
					access_token,
				})
				console.log('getShopNewToken', getShopNewToken)
				if (getShopNewToken.code == 10000) {
					await Shop.findOneAndUpdate(
						{ shop_id: getShopNewToken.data.shop_id },
						{
							$set: {
								access_token_update_time: new Date(),
								...getShopNewToken.data,
							},
						},
						{ new: true, upsert: true }
					)
					ctx.headers.access_token = getShopNewToken.data.access_token
					ctx.headers.shop_name = getShopNewToken.data.shop_name
					ctx.headers.shop_id = getShopNewToken.data.shop_id
					return await next()
				}
				if (getShopNewToken.code == 50002) {
					ctx.body = {
						code: 4390,
						msg: '超过14天未使用, 需要重新授权',
						url: process.env.AUTHORIZATION_URL,
						title: '未授权使用',
						button: '前往授权',
					}
					return
				}
				ctx.body = {
					code: 43896,
					msg: getShopNewToken,
				}
				// 保存数据后next()
			} else {
				ctx.headers.access_token = access_token
				ctx.headers.shop_name = shop_name
				ctx.headers.shop_id = shop_id
				const endTimeDate = new Date(service_end_time * 1000)
				// console.log('endTimeDate', endTimeDate)
				const nowDate = new Date()
				// console.log('nowDate', nowDate)

				if (endTimeDate < nowDate) {
					ctx.body = {
						code: 4390,
						msg: '授权已到期, 请前往购买授权',
						url: process.env.BUY_URL,
						title: '订购已过期',
						button: '前往订购',
					}
					return
				}
				// 检查授权使用时间是否到期
				// 检查是否已经退款
				await next()
				// ctx.body = 123465
				// return
			}
		}
	}
}

export default cheackShop
